<?php
namespace app\admin\controller;
use think\Db;
use think\Request;
class Depot extends Base
{
	/**
	 * 仓库列表
	 * @return [type] [description]
	 */
	function index(){
		$keywords = Request()->get('keywords');
		$query = Db::table('sdzx_depot')->alias('g')->field('*');
		if ($keywords) {
			$query->where(" depot_name like '%{$keywords}%' ");
		}
		$list=$query->paginate('',false,['query'=>Request()->param()]);
		foreach ($list as $k => $v) {
			$tmp = Db::field('count(goods_id) as cate_num')->name('stock')
			->where(['depot_id'=>$v['depot_id']])
			->group('depot_id')
			->find();
			$v['cate_num'] = $tmp['cate_num'];
			$list[$k] = $v;
		}
		$data['list'] = $list;
		return $this->fetch('index',$data);
	}

	/**
	 * 添加仓库
	 */
	function addDepot(){
		$data = Request()->only('depot_name,remark','post');
		if (empty($data['depot_name'])) {
			$this->error('请填写仓库名');
		}
		//查找仓库是否已经存在
		$has = Db::name('depot')->where(['depot_name'=>$data['depot_name']])->find();
		if ($has) {
			$this->error('仓库已经存在');
		}
		$data['create_time'] = date('Y-m-d H:i:s');
		$re = Db::name('depot')->insert($data);
		if ($re) {
			$data['depot_id']= Db::name('depot')->getLastInsID();
			$this->success('新增成功','',$data);
		}else{
			$this->error('新增失败');
		}
	}

	/**
	 * 删除
	 * @return [type] [description]
	 */
	function delDepot(){
		$ids = Request()->param('ids');
		if (empty($ids)) {
			$this->error('参数错误');
		}
		//仓库里面是否有商品
		$tmp = Db::field('stock_id')->name('stock')->where(['depot_id'=>['in',$ids],'stock_num'=>['neq',0]])->find();
		if ($tmp) {
			$this->error('仓库下面存在商品不能删除');
		}else{
			Db::name('depot')->where(['depot_id'=>['in',$ids]])->delete();
			$this->success('删除成功');
		}
	}
}